package cn.kgc.common.util;

import cn.hutool.core.util.StrUtil;
import cn.kgc.common.constant.ResultConstant;

import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtil {

    private static long tokenExpiration = 365 * 24 * 60 * 60 * 1000;

    private static String tokenSignKey = "8r2ejkd8we";


    public static String createToken(String userId, String userName) {
        String token = Jwts.builder()
                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }


    public static String getUserId(String token) {
        try {
            if (StrUtil.isEmpty(token)) {
                return null;
            }
            Jws<Claims> claimsJws =
                    Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            String userId=(String)claims.get("userId");
            return userId;
        } catch (Exception e) {
            throw new HttpException(ResultConstant.NO_LOGIN);
        }
    }

    public static String getUsername(String token) {
        try {
            if (StrUtil.isEmpty(token)) {
                return "";
            };
            Jws<Claims> claimsJws =
                    Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("userName");
        } catch (Exception e) {
            throw new HttpException(ResultConstant.NO_LOGIN);
        }
    }

}
